<!-- filename: frontend/src/pages/conversation/conversation.vue -->
<template>
  <view class="page-container">
    <!-- 1. 使用全局 Header，并通过 title prop 传入 otherUsername -->
    <Header :title="otherUsername" @open-auth-modal="isAuthModalVisible = true" />
    <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

    <!-- 2. content-wrapper 作为滚动的主体，并有正确的 padding -->
    <view class="content-wrapper">
      <view v-if="isLoading" class="loading-state">正在加载消息...</view>
      <view v-else-if="error" class="error-state">{{ error }}</view>
      
      <view v-else class="chat-container">
        <!-- 3. scroll-view 不再需要，我们让页面自然滚动 -->
        <view class="messages-list">
          <view v-if="messages.length === 0" class="empty-state">开始你们的对话吧！</view>
          <view 
            v-for="msg in messages" 
            :key="msg.id" 
            :id="`msg-${msg.id}`"
            class="message-row" 
            :class="{ 'my-message': msg.sender_id === authStore.user.id }"
          >
            <image 
              :src="msg.sender_avatar_url || '/static/avatars/default.png'" 
              class="avatar-image" 
              mode="aspectFill"
              @click="navigateToUserProfile(msg.sender_id)"
            />
            <view class="message-main">
              <view class="message-bubble">
                <text>{{ msg.content }}</text>
              </view>
            </view>
            <view v-if="msg.sender_id === authStore.user.id" class="message-menu-btn" @click="showDeleteMenu(msg)">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/></svg>
            </view>
          </view>
          <!-- 底部留出空白，防止最后一条消息被输入框遮挡 -->
          <view class="scroll-padding-bottom"></view>
        </view>
      </view>
    </view>

    <!-- 4. 输入框使用 fixed 定位，永远固定在底部 -->
    <view class="input-area">
      <input 
        v-model="newMessageContent"
        class="chat-input" 
        placeholder="输入消息..." 
        confirm-type="send"
        @confirm="sendMessage"
        :disabled="isSending"
      />
      <button class="send-btn" @click="sendMessage" :disabled="isSending || !newMessageContent.trim()">
        {{ isSending ? '...' : '发送' }}
      </button>
    </view>
  </view>
</template>


<script setup>
import { ref, nextTick } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';

const authStore = useAuthStore();
const isAuthModalVisible = ref(false);

const messages = ref([]);
const isLoading = ref(true);
const error = ref('');
const newMessageContent = ref('');
const isSending = ref(false);
let otherUserId = null;
const otherUsername = ref('');

// --- 【核心修改2】重写所有 API 请求函数 ---

const fetchMessages = async () => {
  isLoading.value = true;
  try {
    const data = await request({
      url: `/api/messages/${otherUserId}`,
      method: 'GET'
    });
    if (Array.isArray(data)) {
      messages.value = data;
      // 定位逻辑保持不变
      const lastOpponentMessage = [...data].reverse().find(m => m.sender_id !== authStore.user.id);
      if (lastOpponentMessage) {
        scrollTo(`#msg-${lastOpponentMessage.id}`);
      } else {
        scrollToBottom();
      }
    }
  } catch (err) {
    error.value = err?.data?.error || '加载消息失败';
  } finally {
    isLoading.value = false;
  }
};

const sendMessage = async () => {
  if (!newMessageContent.value.trim() || isSending.value) return;

  isSending.value = true;
  const content = newMessageContent.value;
  newMessageContent.value = '';

  try {
    const data = await request({
      url: `/api/messages`,
      method: 'POST',
      data: {
        receiver_id: otherUserId,
        content: content,
      },
    });
    messages.value.push(data);
    scrollToBottom();
  } catch (error) {
    uni.showToast({ title: error?.data?.error || '发送失败', icon: 'none' });
    newMessageContent.value = content;
  } finally {
    isSending.value = false;
  }
};

const deleteMessage = (messageId) => {
  uni.showModal({
    title: '确认',
    content: '确定要删除这条消息吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await request({
            url: `/api/messages/${messageId}`,
            method: 'DELETE',
          });
          const index = messages.value.findIndex(m => m.id === messageId);
          if (index > -1) {
            messages.value.splice(index, 1);
          }
        } catch (error) {
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    }
  });
};


// --- 无需修改的函数 ---
const scrollTo = (selector) => {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query.select(selector).boundingClientRect(data => {
      if (data) {
        uni.pageScrollTo({
          scrollTop: data.top,
          duration: 0
        });
      }
    }).exec();
  });
};

const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query.select('.messages-list').boundingClientRect(data => {
      if (data && data.height) {
        uni.pageScrollTo({
          scrollTop: data.height,
          duration: 100
        });
      }
    }).exec();
  });
};

const navigateToUserProfile = (userId) => {
  if (!authStore.isLoggedIn) return;
  if (authStore.user && authStore.user.id === userId) {
    uni.switchTab({ url: '/pages/profile/profile' });
    return;
  }
  if (userId) {
    uni.navigateTo({ url: `/pages/user-profile/user-profile?id=${userId}` });
  }
};

const showDeleteMenu = (message) => {
  uni.showActionSheet({
    itemList: ['删除消息'],
    success: (res) => {
      if (res.tapIndex === 0) {
        deleteMessage(message.id);
      }
    }
  });
};

onLoad((options) => {
  otherUserId = Number(options.id);
  otherUsername.value = options.username;

  if (!otherUserId || !otherUsername) {
    error.value = '聊天对象信息不完整';
    isLoading.value = false;
    return;
  }
  
  if (!authStore.isLoggedIn) {
    error.value = '请先登录才能发送私信';
    isLoading.value = false;
    setTimeout(() => { isAuthModalVisible.value = true; }, 500);
    return;
  }
  
  fetchMessages();
});

onUnload(() => {
  authStore.fetchTotalUnreadCounts();
});
</script>

<style scoped lang="scss">
/* 全新的、基于页面滚动的布局 */
.page-container {
  background-color: #f7f7f7;
}

.content-wrapper {
  padding: 60px 0 70px 0; /* 顶部为Header留空，底部为输入框留空 */
}

.chat-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto; /* 居中 */
}

.messages-list {
  padding: 10px;
}

/* 底部输入框，固定在屏幕底部 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  padding: 10px;
  gap: 10px;
  z-index: 100;
  /* 为了居中对齐 */
  max-width: 800px;
  margin: 0 auto;
  box-sizing: border-box;
}

/* 底部留白，防止最后一条消息被输入框遮挡 */
.scroll-padding-bottom {
  height: 20px;
}

/* --- 消息气泡等其他样式保持和上一版一致 --- */
.chat-input { flex: 1; height: 40px; padding: 0 15px; border-radius: 20px; background-color: #f1f1f1; border: none; }
.send-btn { height: 40px; line-height: 40px; background-color: #007aff; color: white; font-size: 14px; &[disabled] { background-color: #a0cfff; } }
.message-row { display: flex; margin-bottom: 20px; gap: 10px; }
.avatar-image { width: 40px; height: 40px; border-radius: 50%; flex-shrink: 0; cursor: pointer; }
.message-main { display: flex; flex-direction: column; max-width: calc(100% - 100px); /* 留出更多边距 */ }
.message-bubble { padding: 10px 15px; border-radius: 12px; font-size: 15px; line-height: 1.5; word-break: break-word; }
.message-row { .message-main { align-items: flex-start; } .message-bubble { background-color: #ffffff; color: #333; } }
.my-message { flex-direction: row-reverse; .message-main { align-items: flex-end; } .message-bubble { background-color: #007aff; color: white; } }
.empty-state { text-align: center; padding-top: 50px; color: #aaa; }
.message-menu-btn {
  align-self: center; /* 垂直居中 */
  padding: 5px;
  margin: 0 5px; /* 增加一些水平边距 */
  color: #aaa;
  cursor: pointer;
  border-radius: 50%;
  opacity: 0; /* 默认隐藏 */
  transition: opacity 0.2s;
}

/* 当鼠标悬浮在自己的消息行上时，显示菜单按钮 */
.my-message:hover .message-menu-btn {
  opacity: 1;
}
</style>